<template>
  <div class="wrapPage-container custom-aboutPage-container">
    <div class="about-body-container">
      <div class="about-left-container">
        <div class="about-left-container">
          <div class="sub-header">
            {{ menuName }}
          </div>
          <div class="tree-container">
            <a-empty v-if="treeData.length == 0" />
            <a-tree
              v-else
              show-icon
              show-line
              v-model="checkedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childList',
                title: 'name',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <template slot="title" slot-scope="{ name }">
                <div class="custom-tree-title-warp">
                  <div class="title" :title="name">
                    {{ name }}
                  </div>
                </div>
              </template>
            </a-tree>
          </div>
        </div>
      </div>
      <div class="about-right-container">
        <div class="version-card">
          <a-descriptions size="small" :column="4">
            <a-descriptions-item label="计划开始时间">
              {{ currentVersion.planStartTime || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="计划结束时间">
              {{ currentVersion.planEndTime || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="总周期">
              {{ currentVersion.duration || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="编制人">
              {{ currentVersion.creator || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="编制时间">
              {{ currentVersion.createTime || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="版本名称">
              {{ currentVersion.name || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="版本号">
              {{ currentVersion.code || "-" }}
            </a-descriptions-item>
            <a-descriptions-item label="状态">
              <span :class="[filterStatusClass(currentVersion.status)]">
                {{ currentVersion.status | filterStatusType }}
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="active-page-container">
          <div
            class="tabs-item"
            :class="[componentKey == 'tableCard' && 'atcive']"
            @click="handleTabActive('tableCard')"
          >
            列表
          </div>
          <div
            class="tabs-item"
            :class="[componentKey == 'ganttCard' && 'atcive']"
            @click="handleTabActive('ganttCard')"
          >
            甘特图
          </div>
          <div class="operate-group">
            <!-- 列表操作项 -->
            <template v-if="componentKey == 'tableCard'">
              <!-- 调整操作项 -->
              <template v-if="pageSource.isOperate">
                <a-button @click="handleEvent('handleCancel')"> 取消 </a-button>
                <a-button
                  @click="handleEvent('handleImport', 2)"
                  v-action="'add_' + moduleSource()"
                >
                  导入
                </a-button>
                <a-button
                  type="primary"
                  @click="handleEvent('handleSubmit')"
                  v-action="'add_' + moduleSource()"
                >
                  提交
                </a-button>
                <a-button
                  type="primary"
                  @click="handleAdd()"
                  v-action="'add_' + moduleSource()"
                >
                  新增
                </a-button>
              </template>
              <!-- 默认操作项 -->
              <template
                v-else-if="!pageSource.isOperate && !pageSource.isPageType"
              >
                <!-- 新增 -->
                <a-button
                  type="primary"
                  @click="handleAdd()"
                  v-if="isSubmit && jsubsystem"
                  v-action="'add_' + moduleSource()"
                >
                  新增
                </a-button>
                <!-- 审批 -->
                <a-button
                  type="primary"
                  @click="handleEvent('handleApprove')"
                  v-if="currentVersion.approveFlag && jsubsystem"
                >
                  审批
                </a-button>
                <!-- 提交 -->
                <a-button
                  type="primary"
                  @click="handleEvent('handleSubmit')"
                  v-if="isSubmit && jsubsystem"
                  v-action="'add_' + moduleSource()"
                >
                  提交
                </a-button>
                <!-- 发布 -->
                <a-button
                  type="primary"
                  @click="handleEvent('handleRelease')"
                  v-if="
                    currentVersion.status == 2 &&
                      currentVersion.publishFlag &&
                      jsubsystem
                  "
                  v-action="'add_' + moduleSource()"
                >
                  发布
                </a-button>
                <!-- 创建/创建 -->
                <a-button
                  type="primary"
                  @click="handleEvent('handleAdjust')"
                  v-if="
                    currentVersion.status == 4 && currentVersion.versionFlag
                  "
                  v-action="'edit_' + moduleSource()"
                >
                  {{ currentVersion.firstFlag ? "创建" : "调整" }}
                </a-button>
                <!-- 展开/折叠 -->
                <a-button @click="handleEvent('handleSwap')">
                  <a-icon type="swap" />
                  展开/折叠
                </a-button>
                <!-- 审批记录 -->
                <a-button
                  @click="handleEvent('handleApprovalRecord')"
                  v-if="isRecord && jsubsystem"
                >
                  审批记录
                </a-button>
                <!-- 下载模版 -->
                <a-dropdown
                  v-if="
                    (currentVersion.status == 0 || !currentVersion.status) &&
                      jsubsystem
                  "
                >
                  <a-menu slot="overlay" @click="downloadTemplate($event)">
                    <a-menu-item :key="1"> Excel模版 </a-menu-item>
                    <a-menu-item :key="2"> Project模版 </a-menu-item>
                  </a-menu>
                  <a-button> 模版下载 <a-icon type="down" /> </a-button>
                </a-dropdown>
                <!-- 导入 -->
                <a-button
                  @click="handleEvent('handleImport', 1)"
                  v-if="
                    (currentVersion.status == 0 || !currentVersion.status) &&
                      jsubsystem
                  "
                  v-action="'add_' + moduleSource()"
                >
                  导入
                </a-button>
                <!-- 导出 -->
                <a-dropdown
                  v-if="currentVersion.status == 4 && currentVersion.status"
                >
                  <a-menu slot="overlay" @click="handleExport($event)">
                    <a-menu-item :key="1"> Excel文件 </a-menu-item>
                    <a-menu-item :key="2"> Project文件 </a-menu-item>
                  </a-menu>
                  <a-button> 导出<a-icon type="down" /> </a-button>
                </a-dropdown>
                <!-- 版本管理 -->
                <a-button @click="handleEvent('handleVersionManage')">
                  版本管理
                  <span
                    class="pending"
                    v-if="currentVersion.hasToDoFlag"
                  ></span>
                </a-button>
              </template>
              <!-- 版本管理 -->
              <template v-else>
                <a-button @click="handleEvent('goBack')">返回</a-button>
              </template>
            </template>
            <!-- 甘特图操作项 -->
            <template v-if="componentKey == 'ganttCard' && treeData.length > 0">
              <a-dropdown>
                <a-menu slot="overlay" @click="ganttChangeDateView($event)">
                  <a-menu-item :key="1"> 日视图 </a-menu-item>
                  <a-menu-item :key="2"> 周视图 </a-menu-item>
                  <a-menu-item :key="3"> 月视图 </a-menu-item>
                  <a-menu-item :key="4"> 季视图 </a-menu-item>
                </a-menu>
                <a-button> {{ ganttText }} <a-icon type="down" /> </a-button>
              </a-dropdown>
            </template>
          </div>
        </div>
        <div class="table-main">
          <!-- 列表 -->
          <tableCard
            ref="tableCard"
            v-if="componentKey == 'tableCard'"
            @ok="handleAdjustOk"
            @versionEditor="handleVersionEdit"
          ></tableCard>
          <!-- 甘特图 -->
          <ganttCard
            ref="ganttCard"
            v-if="componentKey == 'ganttCard'"
          ></ganttCard>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
//列表
import tableCard from "./tableCard.vue";
//甘特图
import ganttCard from "./ganttCard.vue";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
import {
  getPlanControlVersion,
  getTreeList,
  getTreeListDraft,
  getTreeListHistory,
} from "@/api/progressManage";
export default {
  inject: ["moduleSource"],
  provide() {
    return {
      versionSource: () => this.currentVersion,
      treeItemSource: () => this.currentTreeItem,
      conditionsSource: () => this.condition,
      firstIndex: () => this,
    };
  },
  components: {
    ScreenConditions,
    tableCard,
    ganttCard,
  },
  data() {
    return {
      //查询条件
      condition: {
        //项目
        tenantCode: "",
        //名称
        name: "",
        //时间
        defaultTime: [],
      },
      //组件
      componentKey: "tableCard",
      //左侧树
      treeLoading: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      //树节点
      currentTreeItem: {},
      //版本信息
      currentVersion: {},
      //甘特图
      ganttView: 1,
      ganttText: "日视图",
      //操作标识
      pageSource: {
        //是否调整操作按钮
        isOperate: false,
        //是否暂时页面操作权限
        isPageType: null,
        //
        isShow: true,
      },

      //
      isShow: true,
      operateType: 2,
      //
      isAdjust: false,
      isPageType: null,
    };
  },
  filters: {
    //校验状态
    filterStatusType(val) {
      switch (Number(val)) {
        case -1:
          return "待提交";

        case 0:
          return "待提交";

        case 1:
          return "审批中";

        case 2:
          return "审批通过";

        case 3:
          return "驳回";

        case 4:
          return "已发布";

        case 5:
          return "已归档";

        default:
          return "-";
      }
    },
  },
  computed: {
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },

    //【提交】【编辑】权限
    isSubmit() {
      if (
        (this.currentVersion.status == -1 ||
          this.currentVersion.status == 0 ||
          this.currentVersion.status == 3) &&
        this.currentVersion.submitFlag
      ) {
        return true;
      } else {
        return false;
      }
    },

    //审批记录权限
    isRecord() {
      if (this.currentVersion.status && this.currentVersion.status != 0) {
        return true;
      } else {
        return false;
      }
    },

    //子系统不展示
    jsubsystem() {
      if (this.moduleSource() == "scheduleType.01") {
        return true;
      } else {
        return false;
      }
    },
  },
  mounted() {
    this.getVersionData();
  },
  methods: {
    resetButtonGroup() {
      this.pageSource.isOperate = false;
      this.pageSource.isPageType = null;
    },

    handleEvent(event, params) {
      //返回/提交
      if (event == "goBack") {
        this.resetButtonGroup();
        this.getVersionData();
      }
      //返回
      if (event == "handleCancel") {
        this.resetButtonGroup();
      }

      //调用子组件方法
      this.$nextTick(() => {
        this.$refs.tableCard[event](params);
      });
    },

    //新增
    handleAdd() {
      this.$nextTick(() => {
        this.$refs.tableCard.handleEdit({}, 3);
      });
    },

    //下载模版
    downloadTemplate(ev) {
      this.$nextTick(() => {
        this.$refs.tableCard.handleTemplate(ev);
      });
    },

    //导出
    handleExport(ev) {
      this.$nextTick(() => {
        this.$refs.tableCard.handleExport(ev);
      });
    },

    //查询版本号
    getVersionData() {
      return new Promise((reslove, reject) => {
        getPlanControlVersion({
          type: this.moduleSource(),
          orgCode: "",
        })
          .then((res) => {
            this.currentVersion = res?.data ?? {};
            this.getTreeData();
            reslove();
          })
          .catch(() => {
            this.currentVersion = {};
            reject();
          });
      });
    },

    getTreeList,
    getTreeListDraft,
    getTreeListHistory,
    //查询一级节点
    getTreeData() {
      let { uuid = "", status = "" } = this.currentVersion;
      let { componentKey } = this;
      if (!uuid) {
        this.selectedKeys = [];
        this.expandedKeys = [];
        this.currentTreeItem = {};
        this.treeData = [];
        switch (componentKey) {
          case "tableCard":
            this.$nextTick(() => {
              this.$refs.tableCard.clearData();
            });
            break;
          case "ganttCard":
            break;

          default:
            break;
        }
        return;
      }
      this.treeLoading = true;
      return new Promise((resolve, reject) => {
        let apiUrl = "";
        if (status == 4) {
          //正式
          apiUrl = "getTreeList";
        } else if (status == 5) {
          //历史记录
          apiUrl = "getTreeListHistory";
        } else {
          //草稿
          apiUrl = "getTreeListDraft";
        }
        this[apiUrl]({
          versionId: uuid,
          nodeType: this.moduleSource(),
          orgCode: "",
        })
          .then((res) => {
            let source = res?.data || [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.autoExpandParent = true;
            this.treeLoading = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childList");
      let item = flatData.find((v) => !v.childList || v.childList.length == 0);
      this.expandedKeys = [item.uuid];
      this.selectedKeys = [item.uuid];
      this.currentTreeItem = item;
      this.getData();
    },

    //展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.currentTreeItem = info.node.dataRef;
      this.getData();
    },

    getData() {
      let { componentKey } = this;
      this.$nextTick(() => {
        this.$refs[componentKey].getData();
      });
    },

    //甘特图日月年季切换
    ganttChangeDateView(info) {
      let { key } = info;
      this.ganttView = key;
      switch (key) {
        case 1:
          this.ganttText = "日视图";
          break;
        case 2:
          this.ganttText = "周视图";
          break;
        case 3:
          this.ganttText = "月视图";
          break;
        case 4:
          this.ganttText = "季视图";
          break;
        default:
          break;
      }
      this.$nextTick(() => {
        this.$refs.ganttCard.initGantt();
      });
    },

    //新增版本-新版本信息
    handleAdjustOk(data) {
      this.pageSource.isOperate = true;
      this.pageSource.isPageType = 1;
      this.currentVersion = data;
      //刷新左侧树
      this.getTreeData();
    },

    //版本管理-编辑/查看
    handleVersionEdit(data = {}) {
      let { operate, source } = data;
      this.pageSource.isPageType = operate;
      switch (operate) {
        // 编辑
        case 1:
          this.pageSource.isOperate = true;
          break;
        // 查看
        case 2:
          this.pageSource.isOperate = false;
          break;
        default:
          break;
      }
      if (!this.isEmptyObject(source)) {
        this.currentVersion = source;
        //刷新左侧树
        this.getTreeData();
      }
    },

    //Tabs切换
    handleTabActive(key) {
      this.componentKey = key;
      this.getData();
    },

    //是否是空对象
    isEmptyObject(obj) {
      return Object.keys(obj).length == 0;
    },

    //校验状态
    filterStatusClass(val) {
      switch (Number(val)) {
        case -1:
          return "default";

        case 0:
          return "default";

        case 1:
          return "warning";

        case 2:
          return "progress";

        case 3:
          return "reject";

        case 4:
          return "success";

        case 5:
          return "place-file";

        default:
          return "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.wrapPage-container {
  width: 100%;
  .about-right-container {
    .version-card {
      padding: 16px;
      box-sizing: border-box;
      /deep/.ant-descriptions {
        padding: 24px 24px 16px 24px;
        box-sizing: border-box;
        background: #f5f9ff;
        border-radius: 4px 4px 4px 4px;
      }

      .default {
        color: #8c8c8c;
      }
      .success {
        color: #4bc964;
      }
      .warning {
        color: #f07f17;
      }
      .reject {
        color: #ff3f4a;
      }
      .progress {
        color: #a07df1;
      }
      .place-file {
        color: #3b6bf5;
      }
    }
    .active-page-container {
      margin: 0 8px 0 8px;
      display: flex;
      border-bottom: 1px solid #ededed;
      position: relative;
      .tabs-item {
        width: 90px;
        height: 40px;
        background: #f7f7f7;
        border-radius: 4px 4px 0px 0px;
        border-bottom: 0;
        font-size: 14px;
        color: #666666;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 4px;
        cursor: pointer;
        outline: 1px solid #ededed;
        &:first-of-type {
          margin-left: 8px;
        }
        &.atcive {
          transition: all 0.3s;
          color: #1890ff;
          position: relative;
          &::before {
            content: "";
            height: 1px;
            width: 90px;
            background: #fff;
            position: absolute;
            bottom: -1px;
            border-radius: 0 0 4px 4px;
          }
        }
      }
      .operate-group {
        position: absolute;
        right: 32px;
        /deep/.ant-btn {
          margin-right: 16px;
          &:last-of-type {
            margin-right: 0;
          }
        }
        .pending {
          display: inline-block;
          height: 8px;
          width: 8px;
          border-radius: 50%;
          background: #f45353;
          position: absolute;
          top: 2px;
          right: 2px;
        }
      }
    }
    .table-main {
      padding: 10px 16px;
      box-sizing: border-box;
    }
  }
}
</style>
